﻿using B.S.RbacData.Domain.Traceabilitys;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using B.S.RbacData.Read.API.Applications.Commands.Traceabilitys.DeepProcessings;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.RbacData.Read.API.Applications.CommandHandlters.Traceabilitys.DeepProcessings
{
    /// <summary>
    /// 获取深加工信息命令处理
    /// </summary>
    public class GetDeepProcessingCommandHandlter : IRequestHandler<GetDeepProcessingCommand, ApiResult<List<DeepProcessingModel>>>
    {
        private readonly IBaseRepository<DeepProcessingModel> _deepProcessingRepository;

        public GetDeepProcessingCommandHandlter(IBaseRepository<DeepProcessingModel> deepProcessingRepository)
        {
            _deepProcessingRepository = deepProcessingRepository;
        }

        public async Task<ApiResult<List<DeepProcessingModel>>> Handle(GetDeepProcessingCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var deepProcessingList = await _deepProcessingRepository.GetAll()
                    .Where(dp => dp.ProductId == request.ProductId)
                    .OrderByDescending(dp => dp.Creatime)
                    .ToListAsync(cancellationToken);

                return new ApiResult<List<DeepProcessingModel>>
                {
                    code = ResultEnumCode.Ok,
                    data = deepProcessingList,
                    message = deepProcessingList.Any() ? "获取成功" : "未找到相关深加工信息"
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<List<DeepProcessingModel>>
                {
                    code = ResultEnumCode.fails,
                    data = null,
                    message = $"获取深加工信息失败: {ex.Message}"
                };
            }
        }
    }
}
